<template>
  <div>
    <section class="table-box" v-loading="loading" :element-loading-text="$t('unit.loading')">
      <small>{{$t('mill.notice')}}</small>
      <div class="header">
        <div class="area">
          {{$t('dashboard.now_rate')}}：<cu :val="shares_15m | num" :decimals="2"></cu> {{ shares_unit }}H/s
        </div>
        <div class="area">
          <span :class="{active:status==='ALL'}" @click="changetag('ALL')">{{$t('mill.all_machine')}}</span>
          <span :class="{active:status==='ACTIVE'}" @click="changetag('ACTIVE')">{{$t('dashboard.workers_active')}}</span>
          <span :class="{active:status==='INACTIVE'}" @click="changetag('INACTIVE')">{{$t('mill.inworkers_active')}}</span>
          <span :class="{active:status==='DEAD'}" @click="changetag('DEAD')">{{$t('mill.unworkers')}}</span>
        </div>
        <div class="area">
          <input type="text"  :placeholder="$t('mill.search')" v-model="keyword" @keyup.enter="search">
          <i class="iconfont icon-sousuo" @click="search"></i>
        </div>
        <div class="area" @click="startDel" v-show="!obAccessKey">
          {{$t('mill.delete')}}
        </div>
      </div>
      <table>
        <thead>
          <tr>
            <th v-if="isDel">
              <input type="checkbox" id="checkboxAll" v-model="checkboxAll">
              <label for="checkboxAll" class="iconfont" @click="checkboxAllFun"></label>
            </th>
            <th class="pointer" @click="sortChange('worker_name', 1)">{{$t('mill.worker_name')}}<i class="iconfont" :class="[sort1==='asc' ? 'icon-iconset0413' : 'icon-iconset0414']"></i></th>
            <!-- <th>{{$t('mill.node_name')}}</th> -->
            <th class="pointer" @click="sortChange('shares_15m', 2)">{{$t('mill.shares_15m')}}<i class="iconfont" :class="[sort2==='asc' ? 'icon-iconset0413' : 'icon-iconset0414']"></i></th>
            <th class="pointer" @click="sortChange('shares_1h', 3)">{{$t('mill.shares_1h')}}<i class="iconfont" :class="[sort3==='asc' ? 'icon-iconset0413' : 'icon-iconset0414']"></i></th>

            <th class="pointer" @click="sortChange('share_accept', 6)">{{$t('mill.shares_24h')}}<i class="iconfont" :class="[sort6==='asc' ? 'icon-iconset0413' : 'icon-iconset0414']"></i></th>

            <!-- <th>{{$t('mill.accept_count')}}</th> -->
            <th class="pointer" @click="sortChange('reject_rate', 4)">{{$t('mill.reject_rate')}}<i class="iconfont" :class="[sort4==='asc' ? 'icon-iconset0413' : 'icon-iconset0414']"></i></th>
            <th class="pointer" @click="sortChange('last_share_time', 5)">{{$t('mill.share_time')}}<i class="iconfont" :class="[sort5==='asc' ? 'icon-iconset0413' : 'icon-iconset0414']"></i></th>
            <th>{{$t('mill.status')}}</th>
          </tr>
        </thead>
        <tbody>
          <template v-if="total_count">
            <tr v-for="(item, index) in data" :key="index">
              <td v-if="isDel">
                <template v-if="!item.deletedTime">
                  <input type="checkbox" :id="'checkbox'+index" v-model="item.checkbox">
                  <label :for="'checkbox'+index" class="iconfont"></label>
                </template>
              </td>
              <td>
                <router-link class="todetail" :to="'/pools/mill/'+item.worker_id+'|'+item.node">{{item.worker_name}}</router-link>
              </td>
              <!-- <td>{{$t('mill.node.'+item.node)}}</td> -->
              <td>{{item.shares_15m}} {{item.shares_unit}}H/s</td>
              <td>{{item.shares_1h}} {{item.shares_unit}}H/s</td>
              <td>{{item.shares_24h}} {{item.shares_unit}}H/s</td>
              <!-- <td>{{item.accept_count}}</td> -->
              <td>{{(item.reject_rate * 100).toFixed(2)}}%</td>
              <td>{{item.share_time}}</td>
              <td class="status" :class="item.status.toLowerCase()">{{item.status === 'ACTIVE' ? $t('dashboard.active') : ( item.status === 'INACTIVE' ? $t('dashboard.inactive') : $t('dashboard.invalid') )}}</td>
              <div class="mask" :style="'top:'+(38+60*index)+'px'" v-if="item.status==='DEAD' && item.deletedTime">{{$t('mill.delete_lose')}}
                <countdown @countdownend="delCountdown(item.deletedTime)" :startTime="parseInt(item.deletedTime, 10)" :time="130" />s{{$t('mill.start')}}</div>
            </tr>
          </template>
          <template v-else>
            <tr>
              <td colspan="8">{{$t('unit.no_data')}}</td>
            </tr>
          </template>
        </tbody>
      </table>
    </section>
    <Pagination :page="page | num" :pageSize="pagesize | num" :totalCount="total_count | num" :disabled="loading" :sizeChange="sizeChange" :currentChange="currentChange" />
  </div>
</template>
<script>
import Pagination from '@/components/Pagination';
import cu from '@/components/CountUp';
import countdown from '@/components/Countdown';
import { workerStats, workerList, setDelworke } from '@/api';
import { mapGetters } from 'vuex';

export default {
  components: {
    Pagination,
    cu,
    countdown,
  },
  data() {
    return {
      shares_15m: '',
      shares_unit: '',
      workerStatsLoading: false,
      page: 1,
      pagesize: 10,
      total_count: 0,
      status: 'ALL',
      order_by: 'worker_name',
      sort: 'asc',
      sort1: 'asc',
      sort2: 'asc',
      sort3: 'asc',
      sort4: 'asc',
      sort5: 'asc',
      sort6: 'asc',
      keyword: '',
      isDel: false,
      checkboxAll: false,
      data: [],
      loading: false,
      timer: undefined,
      deletedMillCache:
        JSON.parse(window.localStorage.getItem('deletedMillCache')) || {}, // null 或 object
    };
  },
  computed: {
    ...mapGetters(['subCuid', 'obAccessKey']),
  },
  created() {
    this.getWorkerStats();
    this.getWorkerList();
    this.timer = setInterval(() => {
      this.getWorkerStats();
    }, 15000);
  },
  beforeDestroy() {
    clearInterval(this.timer);
  },
  watch: {
    subCuid() {
      this.page = 1;
      this.pagesize = 10;
      this.status = 'ALL';
      this.order_by = 'worker_name';
      this.sort = 'asc';
      this.keyword = '';
      this.getWorkerList();
    },
    status(val) {
      if (val !== 'DEAD') {
        this.isDel = false;
      }
      this.getWorkerList();
    },
    data: {
      handler(val) {
        this.checkboxAll = !val.some(v => !v.checkbox);
      },
      deep: true,
    },
  },
  methods: {
    delCountdown(deletedTime) {
      this.data = this.data.filter(v => v.deletedTime !== deletedTime);
      Object.keys(this.deletedMillCache).forEach((key) => {
        if (key === deletedTime) {
          delete this.deletedMillCache[key];
        }
      });
      window.localStorage.setItem(
        'deletedMillCache',
        JSON.stringify(this.deletedMillCache),
      );
    },
    checkboxAllFun() {
      this.data.forEach((item, index) => {
        this.data[index].checkbox = !this.checkboxAll;
      });
    },
    search() {
      this.getWorkerList();
    },
    sortChange(val, sortIndex) {
      this.order_by = val;
      if (this[`sort${sortIndex}`] === 'asc') {
        this.sort = 'desc';
        this[`sort${sortIndex}`] = 'desc';
      } else {
        this.sort = 'asc';
        this[`sort${sortIndex}`] = 'asc';
      }
      this.getWorkerList();
    },
    startDel() {
      if (this.isDel) {
        const dels = this.data
          .filter(val => val.checkbox)
          .map(val => val.worker_id);
        if (dels.length) {
          this.delworke(dels);
        } else {
          this.$message({
            message: this.$t('mill.select_delet'),
            type: 'warning',
          });
        }
      } else {
        this.isDel = true;
        this.status = 'DEAD';
      }
    },
    getWorkerStats() {
      if (this.workerStatsLoading) {
        return;
      }
      this.workerStatsLoading = true;
      workerStats({
        puid: this.subCuid,
      })
        .then((res) => {
          if (res.data.status === 1) {
            const data = res.data.data;
            this.shares_15m = data.shares_15m;
            this.shares_unit = data.shares_unit;
          }
          this.workerStatsLoading = false;
        })
        .catch(() => {
          this.workerStatsLoading = false;
        });
    },
    getWorkerList() {
      if (this.loading) {
        return;
      }
      this.loading = true;
      workerList({
        puid: this.subCuid,
        page: this.page,
        pagesize: this.pagesize,
        status: this.status,
        order_by: this.order_by,
        sort: this.sort,
        keyword: this.keyword.trim(),
      })
        .then((response) => {
          if (response.data.status === 1) {
            const data = response.data.data;
            const newTime = new Date().getTime(); // 最新时间
            this.data = data.list.map((v, i) => {
              data.list[i].checkbox = false;
              Object.keys(this.deletedMillCache).forEach((key) => {
                if (parseInt(key, 10) + (1000 * 130) <= newTime) {
                  delete this.deletedMillCache[key];
                } else {
                  this.deletedMillCache[key].forEach((value) => {
                    if (value === v.worker_id) {
                      data.list[i].deletedTime = key;
                    }
                  });
                }
              });
              window.localStorage.setItem(
                'deletedMillCache',
                JSON.stringify(this.deletedMillCache),
              );
              return data.list[i];
            });
            this.page = data.page;
            this.pagesize = data.page_size;
            this.total_count = data.total_count;
          }
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    delworke(dels) {
      this.$confirm(this.$t('mill.delete_info'), this.$t('mill.tip'), {
        confirmButtonText: this.$t('btn.confirm'),
        cancelButtonText: this.$t('btn.cancel'),
        type: 'warning',
      })
        .then(() => {
          setDelworke({
            puid: this.subCuid,
            workeid: dels,
          })
            .then((res) => {
              if (res.data.status === 1) {
                const newTime = new Date().getTime(); // 最新时间
                Object.keys(this.deletedMillCache).forEach((key) => {
                  if (parseInt(key, 10) + (1000 * 130) <= newTime) {
                    delete this.deletedMillCache[key];
                  }
                });
                if (this.deletedMillCache[newTime]) {
                  this.deletedMillCache[newTime].push(...dels);
                } else {
                  this.deletedMillCache[newTime] = dels;
                }
                window.localStorage.setItem(
                  'deletedMillCache',
                  JSON.stringify(this.deletedMillCache),
                );
                this.data = this.data.filter(val => !val.checkbox);
                this.getWorkerList();
                this.$message({
                  type: 'success',
                  message: this.$t('mill.delete_success'),
                });
              }
              this.workerStatsLoading = false;
            })
            .catch(() => {
              this.workerStatsLoading = false;
            });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: this.$t('mill.delete_cancel'),
          });
        });
    },
    changetag(value) {
      this.status = value;
    },
    sizeChange(pagesize) {
      this.pagesize = pagesize;
      this.getWorkerList();
    },
    currentChange(page) {
      this.page = page;
      this.getWorkerList();
    },
  },
};
</script>
<style lang="scss" scoped>
.area {
  height: 30px;
  line-height: 28px;
  border-width: 1px;
  border-style: solid;
  font-size: 12px;
  margin-top: 10px;
  border-radius: 3px;
  &:first-of-type {
    border-color: transparent;
    color: #333;
  }
  &:nth-of-type(2) {
    display: flex;
    background-color: #fff;
    border-color: #eaeaea;
    width: 360px;
    span {
      display: inline-block;
      text-align: center;
      flex-grow: 1;
      border-right: 1px solid #eaeaea;
      cursor: pointer;
      &.active {
        background-color: #247ba0;
        color: #fff;
      }
      &:last-of-type {
        border: none;
      }
    }
  }
  &:nth-last-of-type(2) {
    border-color: #eaeaea;
    background-color: #fff;
    position: relative;
    input {
      border: none;
      outline: none;
      height: 28px;
      width: 288px;
      vertical-align: top;
      padding: 0 30px 0 10px;
    }
    i {
      position: absolute;
      top: 0;
      right: 8px;
      font-size: 15px;
      color: #ccc;
      cursor: pointer;
    }
  }
  &:last-of-type {
    border-color: transparent;
    color: #247ba0;
    padding: 0 13px;
    cursor: pointer;
  }
}
</style>

